<?php

namespace app\saas\service;

use app\common\model\trAdmin;
use app\common\model\trOrder;
use app\common\model\trUser;
use app\common\util\ErrorCode;
use app\saas\model\trMall;

/**
 * Class Auth
 * @package app\admin\service
 * 商城服务类
 */
class MallService
{
    private $returnData;
    private $params;
    private $adminId = 0;
    private $field = ["name" => "require", "manager_id" => 0, "expired_time" => null]; //填入数据库需要存储的表字段
    private $fieldMsg = ["name" => "商城名"];
    private $data = [];
    private $isSuper = false;

    public function __construct($data, $param = null, $isSuper = false)
    {
        $this->returnData = $data;
        $this->params = $param;
        $this->adminId = request()->manageData["id"];
        $this->isSuper = $isSuper;
    }

    // 商城列表
    public function pageListRun(){
        $page = isset($this->params['page']) ? $this->params['page'] : 1;
        $pageSize = isset($this->params['pageSize']) ? $this->params['pageSize'] : 10;
        //搜索条件
        if(!$this->isSuper){ // 不是超管，只显示自己的账号列表
            $filter[] = ["manager_id", "=", $this->adminId];
        }
        $filter[] = ["is_delete", "=", (isset($this->params["deleteStatus"]) && $this->params["deleteStatus"] == "1") ? "1" : "0"];
        if(!empty($this->params['search'])){
            $filter[] = ['name', 'like', "%{$this->params["search"]}%"];
        }
        $data = trMall::getList("id,name,expired_time,create_time,manager_id,is_disable", $filter, $page, $pageSize, "create_time desc");
        if(!$data["data"]){
            $this->returnData['data'] = ['list' => [], 'totalPage' => $page, 'currentPage' => $page, 'count' => 0];
        }else {
            $userModel = new trUser();
            $orderModel = new trOrder();
            foreach ($data['data'] as &$item){
                $item["userCount"] = $userModel->getCount(["mall_id" => $item["id"]]);
                $item["orderCount"] = $orderModel->getCount(["mall_id" => $item["id"]]);
                $item["managerUrl"] = $item["isDisable"] == '0' ? request()->domain()."/index.html#/workbench/index?SaaSToken={$this->params["token"]}&SaaSId={$item["id"]}" : '';
                $item["userUrl"] = $item["isDisable"] == '0' ? request()->domain()."/index.html#/workbench/index?SaaSToken={$this->params["token"]}&SaaSId={$item["id"]}" : '';
                if(!empty($item["expiredTime"])){
                    if($item["expiredTime"] < time()){
                        $item["managerUrl"] = '';
                        $item["userUrl"] = '';
                    }
                    $item["expiredTime"] = date("Y-m-d", $item["expiredTime"]);
                }else{
                    $item["expiredTime"] = "永久";
                }
            }
            $this->returnData['data'] = ['list' => $data['data'], 'totalPage' => $data['last_page'], 'currentPage' => $data['current_page'], 'count' => $data['total']];
        }
        return $this->returnData;
    }

    public function toAdd(){
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($this->params[$ks])) {
                return ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
            }
            $this->data[$k] = isset($this->params[$ks]) ? trim($this->params[$ks]) : $v;
        }
        $this->data["manager_id"] = $this->adminId;
        $adminData = trAdmin::getAdminInfo($this->adminId, "expired_time,app_count");
        if(empty($this->data["expired_time"])) {
            $this->data["expired_time"] = $adminData["expiredTime"];
        }else{
            $this->data["expired_time"] = !is_numeric($this->data["expired_time"]) ? strtotime($this->data["expired_time"]) : $this->data["expired_time"];
        }
        if(is_numeric($adminData["appCount"]) && $adminData["appCount"] <= trMall::getCount(["manager_id" => $this->adminId])){
            return ErrorCode::code("customized", "已超过可创建商城数量");
        }
        if(trMall::getCount(["name" => $this->data["name"]])){
            return ErrorCode::code("customized", "商城名称已存在");
        }
        $res = trMall::toAdd($this->data);
        if(isset($res["code"])){
            return $res;
        }
        $this->returnData["msg"] = "添加成功";
        return $this->returnData;
    }

    public function getInfo(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "商城ID");
        }
        $data = trMall::getFields("id,name,manager_id", ["id" => $this->params["id"]]);
        if($data){
            if(!$this->isSuper && $data["managerId"] != $this->adminId){
                return ErrorCode::code("customized", "您无权限操作");
            }
            unset($data["managerId"]);
//            if(!empty($data["expiredTime"])){
//                $data["expiredTime"] = date("Y-m-d", $data["expiredTime"]);
//            }
            $this->returnData["data"] = $data;
        }else{
            $this->returnData["data"] = [];
        }
        return $this->returnData;
    }

    // 更新
    public function toUpdate(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "商城ID");
        }
        foreach ($this->field as $k => $v) {
            $ks = parse_name($k); //转换字段，变驼峰
            if ($v === 'require' && !isset($this->params[$ks])) {
                return ErrorCode::code("params_not_exist", $this->fieldMsg[$k]);
            }
            if (isset($this->params[$ks])) {
                $this->data[$k] = trim($this->params[$ks]);
            }
        }
        if(request()->manageData["type"] == '3'){ // 由其它系统创建的账号不允许修改
            unset($this->data["expired_time"]);
        }else {
            if(isset($this->data["expired_time"])) {
                $this->data["expired_time"] = !is_numeric($this->data["expired_time"]) ? strtotime($this->data["expired_time"]) : $this->data["expired_time"];
            }else{
                $this->data["expired_time"] = null;
            }
        }
        if($this->isSuper) {
            $res = trMall::doUpdate($this->data, ["id" => $this->params["id"]]);
        }else{
            $res = trMall::doUpdate($this->data, ["id" => $this->params["id"], "manager_id" => $this->adminId]);
        }
        if(isset($res["code"])){
            return $res;
        }
        $this->returnData["msg"] = "修改成功";
        return $this->returnData;
    }

    // 删除
    public function toDelete(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "商城ID");
        }
        if($this->isSuper) {
            $res = trMall::getCount(["id" => $this->params["id"]]);
            if(trMall::getCount(["manager_id" => $this->adminId]) <= 1){
                return ErrorCode::code("customized", "超管最后一个商城不能删除");
            }
        }else{
            $res = trMall::getCount(["id" => $this->params["id"], "manager_id" => $this->adminId]);
        }
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "商城不存在";
        }else {
            trMall::delById($this->params["id"]);
            $this->returnData["msg"] = "删除成功";
        }
        return $this->returnData;
    }

    // 回收
    public function toRecycle(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "商城ID");
        }
        if(!isset($this->params["deleteStatus"]) || !in_array($this->params["deleteStatus"], ["0", "1"])){
            return ErrorCode::code("params_error", "status");
        }
        $this->data["is_delete"] = $this->params["deleteStatus"];
        if($this->isSuper) {
            $res = trMall::doUpdate($this->data, ["id" => $this->params["id"]]);
        }else{
            $res = trMall::doUpdate($this->data, ["id" => $this->params["id"], "manager_id" => $this->adminId]);
        }
        if(isset($res["code"])){
            return $res;
        }
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "状态更新失败";
        }else {
            $this->returnData["msg"] = "状态更新成功";
        }
        return $this->returnData;
    }

    // 禁用
    public function toDisable(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "商城ID");
        }
        if(!isset($this->params["status"]) || !in_array($this->params["status"], ["0", "1"])){
            return ErrorCode::code("params_error", "status");
        }
        $this->data["is_disable"] = $this->params["status"];
        if($this->isSuper) {
            $res = trMall::doUpdate($this->data, ["id" => $this->params["id"]]);
        }else{
            $res = trMall::doUpdate($this->data, ["id" => $this->params["id"], "manager_id" => $this->adminId]);
        }
        if(isset($res["code"])){
            return $res;
        }
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "状态更新失败";
        }else {
            $this->returnData["msg"] = "状态更新成功";
        }
        return $this->returnData;
    }

    // 迁移
    public function toMigrate(){
        if(empty($this->params['id'])){
            return ErrorCode::code("params_not_exist", "商城ID");
        }
        if(empty($this->params['managerId'])){
            return ErrorCode::code("params_not_exist", "管理员ID");
        }
        if(!$this->isSuper) {
            return ErrorCode::code("customized", "您无权限操作");
        }
        if(!trAdmin::where("id", $this->params["managerId"])->count()){
            return ErrorCode::code("customized", "管理员不存在");
        }
        $res = trMall::doUpdate(["manager_id" => $this->params["managerId"]], ["id" => $this->params["id"]]);
        if(isset($res["code"])){
            return $res;
        }
        if(!$res){
            $this->returnData = ErrorCode::code("fail");
            $this->returnData["msg"] = "迁移失败";
        }else {
            $this->returnData["msg"] = "迁移成功";
        }
        return $this->returnData;
    }
}